import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/employee_list_data.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/net/response/service_order_ddetail_data.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/viewmodel/service_order/service_order_detail_info_view_model.dart';
import 'package:ls_work/viewmodel/service_order/service_order_home_view_model.dart';
import 'package:ls_work/widgets/add_image_widget.dart';
import 'package:ls_work/widgets/requir_text_view.dart';
import 'package:ls_work/widgets/title_value_widget.dart';

import '../../a_elder/models/code_value_entity.dart';
import '../../ui/service_order/multi_choose_employee_page.dart';
import '../../util/location_utils.dart';
import '../model/combo_data_model.dart';
import '../new_yyt_view_model.dart';

class FinishServiceOrderViewModel extends BaseViewModel {
  final ServiceOrderDdetailData detailData;

  FinishServiceOrderViewModel(BuildContext context,this.detailData) : super(context) {
    canEdit = detailData.serveRequestOrderId == null;
    var price = detailData.originalPrice?.toDouble() ?? 0;

    if (detailData.orderServeTypeName?.contains("用餐") == true) {
      isFoodService = true;
    } else {
      isFoodService = false;
    }
    siteName = detailData.site ?? "";
    if (!canEdit) {
      realPrice = price.toString();
      payId = "";
      payType = detailData.payWayName ?? "";
      if (price > 0) {
        needPay = "收费";
      } else {
        needPay = "免费";
      }
    }
  }

  var canEdit = true;

  var isFoodService = false;

  static const format = [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn];
  var finishTime = DateTime.now().toDateStr(format);

  ///服务说明
  var info = "";

  ///支付费用
  var needPay = "免费";

  ///支付方式
  var payType = "";
  var payId = "10326";

  String? payStatusName;
  int? payStatus;

  ///实际费用
  var realPrice = "";

  ///协作人
  var commonExecutorName = "";
  var commonExecutorId = "";

  ///使用物料
  var selectGoods = <UseGoodModel>[];

  var needGoods = false;

  List<String> files = [];

  var comboModel = ComboDataModel();

  List<CodeValue> siteList = [];

  String siteName = "";

  var locationAddress = "";
  double? longitude;
  double? latitude;

  void chooseSite() {
    var current = siteList.firstWhere((element) => element.nameCn == siteName,
        orElse: () => siteList.first);
    DataPickerView(context, siteList, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
      siteName = siteList[p1].nameCn ?? "";
      notifyListeners();
    }).show();
  }

  Future<void> requestSiteCombo() async {
    try {
      siteList = await comboModel.getComboData("556670");
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  Widget content() {
    return ListView(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      children: [
        TitleValueWidget(
          '站点',
          text: siteName,
          showArrow: true,
        ).onTap(() {
          chooseSite();
        }),
        Gaps.dividerLine,
        TitleValueWidget(
          '服务完成时间',
          text: finishTime,
          showArrow: false,
        ),
        Gaps.dividerLine,
        TitleValueWidget(
          '定位',
          text: locationAddress,
          showArrow: false,
          hint: "等待定位完成",
        ),
        Gaps.dividerLine,
        TitleValueWidget(
          '责任部门',
          text: NewYytViewModel.userInfo?.officeName ?? "",
          showArrow: false,
        ),
        Gaps.dividerLine,
        TitleValueWidget(
          '责任人',
          text: NewYytViewModel.userInfo?.name ?? "",
          showArrow: false,
        ),
        Gaps.dividerLine,
        TitleValueWidget(
          '协作人',
          text: commonExecutorName,
          showArrow: true,
        ).onTap(() {
          chooseTogether();
        }),
        Gaps.dividerLine,
        CommonText('服务说明').addToContainer(
            width: double.infinity,
            padding: EdgeInsets.only(left: 16, top: 16, bottom: 10),
            color: Colors.white),
        CommonInput(
          hintText: '请输入描述信息',
          onChanged: (str) {
            info = str;
          },
          border: InputBorder.none,
          padding: EdgeInsets.zero,
          keyboardType: CommonInputType.multiline,
          isDense: true,
        ).addToContainer(
            padding: EdgeInsets.symmetric(horizontal: 16), color: Colors.white),
        Gaps.dividerLine,
        TitleValueWidget(
          '支付费用',
          isRequired: true,
          text: needPay,
        ).onTap(() {
          if (!canEdit) {
            return;
          }
          selectNeedPay();
        }),
        payInfoWidget(),
        Container(
          height: 10,
        ),
        goodsInfoWidget(),
        Gaps.dividerLine,
        RequireTextView("上传照片").addToContainer(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            color: Colors.white,
            width: double.infinity),
        AddImageWidget(
          (file) {
            this.files = file;
          },
          files: this.files,
          cameramsg: "拍摄工单处理照片，需要申请您的相机权限",
          photomsg: "从相册选取工单处理照片，需要申请您的相册权限",
        ).addToContainer(color: Colors.white),
        Gaps.dividerLine,
        ElevatedButton(
                onPressed: () {
                  finishClick();
                },
                style: ButtonStyle(
                    shape: WidgetStateProperty.all(StadiumBorder()),
                    minimumSize:
                        WidgetStateProperty.all(Size(double.infinity, 40))),
                child: CommonText(isFoodService ? '完成' : '完成服务',
                    textColor: Colors.white))
            .addToContainer(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
                color: Colors.white)
      ],
    );
  }

  ///支付信息
  Widget payInfoWidget() {
    return needPay == "免费"
        ? Container()
        : Column(
            children: [
              Gaps.dividerLine,
              TitleValueWidget(
                '支付方式',
                hint: '请选择支付方式',
                text: payType,
                isRequired: true,
              ).onTap(() {
                if (!canEdit) {
                  return;
                }
                selectPayType();
              }),
              Gaps.dividerLine,
              TitleValueWidget(
                '预计金额',
                text: '¥${detailData.originalPrice ?? ""}',
                showArrow: false,
              ),
              Gaps.dividerLine,
              Row(
                children: [
                  RequireTextView('实际费用').setWeight(2),
                  (canEdit
                          ? CommonInput(
                              hintText: '请输入实际费用',
                              border: InputBorder.none,
                              padding: EdgeInsets.zero,
                              isDense: true,
                              text: realPrice,
                              onChanged: (str) {
                                realPrice = str;
                              },
                              keyboardType: CommonInputType.numberAndDecimal,
                            )
                          : CommonText(realPrice))
                      .addToContainer(
                          decoration: BoxDecoration(color: Colours.bg_color),
                          padding:
                              EdgeInsets.symmetric(horizontal: 8, vertical: 4))
                      .setWeight(3)
                ],
              ).addToContainer(
                  color: Colors.white,
                  padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10)),

              // TitleValueWidget(
              //   '收款状态',
              //   hint: '请选择收款状态',
              //   text: payStatusName??"",
              //   isRequired: true,
              // ).onTap(() {
              //   choosePayStatus();
              // }),
            ],
          );
  }

  void choosePayStatus() {
    var items = [
      PickerDataWithIdModel(pickId: '0', pickName: '待收款'),
      PickerDataWithIdModel(pickId: '1', pickName: '已收款'),
    ];
    var current = payStatus == null
        ? null
        : items.firstWhere((e) => e.pickId?.toInt() == payStatus);
    DataPickerView(context, items, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
      var item = items[p1];
      payStatus = item.pickId?.toInt();
      payStatusName = item.name;
      notifyListeners();
    }).show();
  }

  ///选择是否支付费用
  void selectNeedPay() {
    var items = [
      PickerDataWithIdModel(pickName: "免费", pickId: '10326'),
      PickerDataWithIdModel(pickName: "收费", pickId: '')
    ];
    DataPickerView(context, items, onSubmitListener: (p1, p2, p3) {
      var item = items[p1];
      needPay = item.pickName ?? "";
      payId = item.pickId ?? "";
      payType = "";
      notifyListeners();
    }).show();
  }

  ///选择支付方式
  void selectPayType() {
    var items = [
      PickerDataWithIdModel(pickName: "现金", pickId: '10324'),
      PickerDataWithIdModel(pickName: "电子支付", pickId: '10325')
    ];
    DataPickerView(context, items, onSubmitListener: (p1, p2, p3) {
      var item = items[p1];
      payType = item.name;
      payId = item.pickId ?? "";
      notifyListeners();
    }).show();
  }

  Widget goodsInfoWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        needGoods
            ? Row(
                children: [
                  CommonText('使用物料', fontWeight: FontWeight.w600).setWeight(1),
                  CommonText('+ 增加').addToContainer().onTap(() {
                    if (selectGoods.isEmpty) {
                      selectGoods.add(UseGoodModel());
                    } else {
                      if (selectGoods.last.goodName.isNullOrEmpty()) {
                        showToast("请选择物料");
                        return;
                      }
                      if (selectGoods.last.goodNumber.isNullOrEmpty()) {
                        showToast('请输入使用数量');
                        return;
                      }
                      selectGoods.add(UseGoodModel());
                    }
                    notifyListeners();
                  })
                ],
              ).addToContainer(
                width: double.infinity,
                color: Colors.white,
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16))
            : Container(),
        ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              var item = selectGoods[index];
              return Row(
                children: [
                  Column(
                    children: [
                      TitleValueWidget(
                        '物料使用',
                        isRequired: true,
                        hint: '请选择',
                      ),
                      Gaps.dividerLine,
                      Row(
                        children: [
                          RequireTextView('使用数量').setWeight(2),
                          CommonInput(
                            hintText: '请输入使用数量',
                            border: InputBorder.none,
                            padding: EdgeInsets.zero,
                            isDense: true,
                            onChanged: (str) {
                              item.goodNumber = str;
                            },
                            keyboardType: CommonInputType.numberAndDecimal,
                          )
                              .addToContainer(
                                  decoration:
                                      BoxDecoration(color: Colours.bg_color),
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 8, vertical: 4))
                              .setWeight(3)
                        ],
                      ).addToContainer(
                          color: Colors.white,
                          padding: EdgeInsets.symmetric(
                              horizontal: 16, vertical: 10))
                    ],
                  ).setWeight(1),
                  Icon(Icons.delete_forever_rounded).onTap(() {
                    selectGoods.remove(item);
                    notifyListeners();
                  }),
                  Container(
                    width: 10,
                  )
                ],
              ).addToContainer(color: Colors.white);
            },
            separatorBuilder: (context, index) {
              return Gaps.dividerLine;
            },
            itemCount: selectGoods.length),
      ],
    );
  }

  void finishClick() {
    // if (info.isNullOrEmpty()) {
    //   showToast("请输入描述信息");
    //   return;
    // }

    if (needPay == "收费") {
      if (payType.isEmpty&&canEdit) {
        showToast('请选择支付方式');
        return;
      }
      if (realPrice.isNullOrEmpty()) {
        showToast('请输入实际费用');
        return;
      }
      if (realPrice.toDouble() == 0) {
        showToast('实际费用不可为0');
        return;
      }

      // if(payStatus==null){
      //   showToast('请选择收款状态');
      //   return;
      // }
    }
    if (files.isEmpty) {
      showToast('请选择照片');
      return;
    }

    submitFinish();
  }

  ///上传文件
  Future<List<Map<String, dynamic>>> _uploadFiles() async {
    List<Map<String, dynamic>> result = [];
    for (var file in files) {
      var data = await PostRequest.uploadFile(file);
      var bean = ResponseBean.fromJson(data);
      if ('0' == bean.code) {
        result.add(bean.data);
      } else {
        throw bean.msg ?? "";
      }
    }
    return result;
  }

  Future<void> submitFinish() async {
    showLoadingDialog();
    try {
      var uploadFiles = await _uploadFiles();
      var result = await PostRequest.finishService(
          detailData.id.toString(),
          finishTime,
          info,
          needPay == '免费' ? "0" : realPrice,
          payId,
          uploadFiles,
          commonExecutorName,
          commonExecutorId,
          needPay == '免费' ? null : payStatus,
          site: siteName,
          longitude: longitude,
          latitude: latitude,
          serveAddress: locationAddress);
      var bean = ResponseBean.fromJson(result);
      hideDialog();
      if ("0" == bean.code) {
        showToast('完成服务');
        sendMessage(SendMessageEvent(MessageConfig.REFRESH_ORDER));
        finish();
      } else {
        showToast(bean.msg ?? "");
      }
      hideDialog();
    } catch (e) {
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if (event.msgCode == MessageConfig.SEND_DETAIL_DATA) {
      // detailData = event.obj;
      notifyListeners();
    }
  }

  Future<void> chooseTogether() async {
    var list = await Go().push(MultiChooseEmployeePage());
    if (list != null) {
      var data = list as List<EmployeeListData>;
      commonExecutorId = data.map((e) => e.humanId).join(",");
      commonExecutorName = data.map((e) => e.userName).join(",");
      notifyListeners();
    }
  }

  OnLocationResultListener? locationListener;

  @override
  void onCreated() {
    super.onCreated();
    requestSiteCombo();
    locationListener = (location) {
      if(!location.city.isNullOrEmpty()){
        locationAddress = (location.address ?? "").replaceAll("中国", "");
        longitude = location.longitude;
        latitude = location.latitude;
        notifyListeners();
        debugPrint("locationAddress:$locationAddress");
      }
    };
    LocationConfig.instance.addListener(locationListener!);

    LocationConfig.instance.myLocPlugin.startLocation();
  }

  @override
  void dispose() {
    if (locationListener != null) {
      LocationConfig.instance.removeListener(locationListener!);
    }
    LocationConfig.instance.stop();
    super.dispose();
  }
}

class UseGoodModel {
  String? goodName;
  String? goodId;
  String? goodNumber;

  UseGoodModel({this.goodName, this.goodId, this.goodNumber});
}
